#include "MjpgWidget.h"
#include <QPainter>
#include <QNetworkReply>
#include <QAuthenticator>
#include <QHttp>
#include <QUrl>
#include <QDebug>

MjpgWidget::MjpgWidget(QWidget *parent) :
    QWidget(parent),
    _nwkManager(NULL), _picReply(NULL),
    _host("127.0.0.1"), _port(80),
    drawIdx(0), recvIdx(1)
{
}

MjpgWidget::~MjpgWidget()
{
    if(_nwkManager)
    {
        _nwkManager->deleteLater();
    }
}

void MjpgWidget::paintEvent(QPaintEvent *ev)
{
    QPainter pt(this);
    QRect rc;
    QPixmap pixmap;
    pixmap.loadFromData(picData[drawIdx]);
    rc = this->geometry();
    pt.drawPixmap(0, 0, rc.width(), rc.height(), pixmap);
}

void MjpgWidget::sendRequest()
{
    if(_nwkManager == NULL)
        return;
    QUrl url;
    url.setScheme("http");
    url.setHost(_host);
    url.setPort(_port);
    url.setPath(uri);
    QNetworkRequest req(url);
    _picReply = _nwkManager->get(req);
}

void MjpgWidget::start(const QString &host, quint16 port,
                       const QString &uri,
                       const QString &userName, const QString &passWord)
{
    if(_nwkManager != NULL)
        return;
    this->uri = uri;
    _nwkManager = new QNetworkAccessManager(this);
    connect(_nwkManager,
            SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
            this,
            SLOT(onNwkAuthenticationRequired(QNetworkReply*,QAuthenticator*)));
    connect(_nwkManager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(onNwkFinished(QNetworkReply*)));

    _host = host;
    _port = port;
    _userName = userName;
    _passWord = passWord;
    sendRequest();
}

void MjpgWidget::stop()
{
    if(_nwkManager == NULL)
        return;
    _nwkManager->deleteLater();
    _nwkManager = NULL;
}

void MjpgWidget::clear()
{
    picData[drawIdx].clear();
    update();
    sendRequest();
}

void MjpgWidget::onNwkAuthenticationRequired(QNetworkReply *reply,
                                             QAuthenticator *authenticator)
{
    qDebug()<<__PRETTY_FUNCTION__;
    authenticator->setUser(_userName);
    authenticator->setPassword(_passWord);
}

void MjpgWidget::onNwkFinished(QNetworkReply *reply)
{
    if(reply != _picReply)
        return;
    qDebug()<<__PRETTY_FUNCTION__;
    picData[recvIdx] = reply->readAll();
    drawIdx = recvIdx;
    recvIdx = !recvIdx;
    update();
    sendRequest();
}

void MjpgWidget::sendGetRequest(const QString &uri)
{
    if(_nwkManager == NULL)
        return;
    QUrl url;
    url.setScheme("http");
    url.setHost(_host);
    url.setPort(_port);
    url.setPath(uri);
    QNetworkRequest req(url);
    _nwkManager->get(req);
}
